var TChannelThrift = require('tchannel/as/thrift');
var TChannel = require('tchannel');
var fs = require('fs');
var path = require('path');

var server = TChannel({
    serviceName: 'server'
});
var client = TChannel();
var tchannelThrift = TChannelThrift({
    channel: client,
    source: fs.readFileSync(
        path.join(__dirname, 'thrift', 'service.thrift'), 'utf8'
    )
});

var context = {};

tchannelThrift.register(server, 'echo', context, echo);
function echo(context, req, head, body, callback) {
    callback(null, {
        ok: true,
        head: head,
        body: body
    });
}

server.listen(4040, '127.0.0.1', onListening);

function onListening() {
    tchannelThrift.request({
        serviceName: 'server',
        host: '127.0.0.1:4040'
    }).send('Echo::echo', {
        someHeader: 'headerValue'
    }, {
        value: 'some-string'
    }, onResponse);

    function onResponse(err, resp) {
        if (err) {
            console.log('got error', err);
        } else {
            console.log('got resp', resp);
        }

        server.close();
    }
}